<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/9/18
 * Time: 17:33
 */
class Wish_activityApp extends BackendApp
{
    protected $_wish_activityModel;
    protected $_wish_goodsModel;
    protected $_goods_mod;

    function __construct()
    {
        $this->Banner_settingApp();
    }

    function Banner_settingApp()
    {
        parent::BackendApp();
        $this->_wish_activityModel = &m('wish_activity');
        $this->_goods_mod = &m('goods');
        $this->_wish_goodsModel = &m('wish_goods');
    }


    function index(){
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'type',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'start_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'end_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            )
        ));
        $page = $this->_get_page(10);
        $res = $this->_wish_activityModel->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'limit' => $page['limit'],
            'count' => true,
            'order' => "activity_id desc"
        ));

        foreach ($res as $k=>$v){
            $res[$k]['type_value'] = wish_activityModel::$typeValue[$v['type']];
        }
        $this->assign('wish_type_list', array(
            1  =>  wish_activityModel::$typeValue[1],
            2  =>  wish_activityModel::$typeValue[2],
        ));

        $page['item_count'] = $this->_wish_activityModel->getCount();   //获取统计的数据
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->display('wish_activity.index.html');
    }

    function add(){
        if($_POST){
            $data = array(
                'remark' => $_POST['remark'],
                'type' => $_POST['type']?$_POST['type']:1,
                'start_time' => strtotime($_POST['start_time']),
                'end_time' => strtotime($_POST['end_time']),
            );
            $goods_id = explode(',',$_POST['goods_id']);
            if(count($goods_id) < 1 || !$_POST['goods_id']){
                $this->show_warning('请选择商品！');
                return;
            }
            if (!$activity_id = $this->_wish_activityModel->add($data)) {  //获取article_id
                $this->show_warning($this->_wish_activityModel->get_error());
                return;
            } else {
                $this->admin_log("新增活动[" . $_POST['remark'] . "] 周期".$_POST['start_time']."-".$_POST['end_time'], 1);
            }

            //处理上传的文章LOGO
            $article_logo = $this->_upload($_FILES,'wish_activity_url');
            if ($article_logo === false) {
                return;
            }
            foreach($goods_id as $k=>$v){
                $newArr['activity_id'] = $activity_id;
                $newArr['goods_id'] = $v;
                $newArr['sort_order'] = $_POST['goodsSorts'][$k];
                $this->_wish_goodsModel->add($newArr);
            }

            $article_logo  && $this->_wish_activityModel->edit($activity_id, array('wish_activity_url' => $article_logo)); //将logo地址记下
            $this->show_message('添加成功', 'back_list', 'index.php?app=wish_activity', 'continue_add', 'index.php?app=wish_activity&amp;act=add'
            );

        }else{
            $yes_or_no = array(
                1  =>  wish_activityModel::$typeValue[1],
                2  =>  wish_activityModel::$typeValue[2],
            );
            $this->assign('yes_or_no', $yes_or_no);
            $this->display('wish_activity.form.html');
        }
    }
    function _upload($file,$str){
        require_once '../includes/aliyunOss/samples/Common.php';
        $image = $file[$str];
        $imageName = date("YmdHis", time()) . rand(1000,10000);
        $path = 'data/files/mall/wish_activity/'.$str;

        if ($image['error'] == UPLOAD_ERR_NO_FILE) { // 没有文件被上传
            return '';
        }
        import('uploader.lib');             //导入上传类
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
        $uploader->addFile($_FILES[$str]); //上传logo
        if (!$uploader->file_info()) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=wish_activity&amp;act=index');
            return false;
        }
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);
        if (!$file_path = $uploader->save($path,$imageName)) {   //保存到指定目录，并以指定文件名$ad_id存储
            $this->show_message('上传文件失败！');
            return false;
        }
        $ossClient = new \common;
        $r = $ossClient->putObjectFile('../'.$file_path,$file_path);
        if(!$r['info'] || $r['info']['http_code'] != 200){
            $this->show_message('上传oss失败！');
            return false;
        }
        unlink('../'.$file_path);
        return $file_path;
    }

    function edit(){

        $ad_id = isset($_GET['activity_id']) ? intval($_GET['activity_id']) : 0;
        if (!$ad_id)
        {
            $this->show_warning('no_such_theme');
            return;
        }

        if (!IS_POST)
        {
            $find_data = $this->_wish_activityModel->find($ad_id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_theme');

                return;
            }
            $ad    =   current($find_data);
            if ($ad['wish_activity_url'])
            {
                $ad['wish_activity_url']  =   WEB_PHOTO_SRC . "/" . $ad['wish_activity_url'];
            }
            /* 显示新增表单 */
            $yes_or_no = array(
                1  =>  wish_activityModel::$typeValue[1],
                2  =>  wish_activityModel::$typeValue[2],
            );

            $sql = "select * from ecm_wish_goods where activity_id = ".$ad_id;
            $resOld = $this->_wish_goodsModel->db->query($sql);
            $goods_spec = &m('goodsspec');
            while ($chat = $this->_wish_goodsModel->db->fetchRow($resOld)) {
                $goodsInfo[] = $chat;
            }

            if(!empty($goodsInfo)){
                $temp_goods = array();
                $ids = '';
                foreach ($goodsInfo as $k => $v){
                    if($k == 0){
                        $ids = $v['goods_id'];
                    }else{
                        $ids .= ','.$v['goods_id'];
                    }
                    $in_array = array();
                    $stock_array = array();
                    $temp_goods[$k]['goods_id'] = $v['goods_id'];
                    $c = $this->_goods_mod->get($v['goods_id']);
                    if(is_array($c) && $c){
                        $temp_goods[$k]['goods_name'] = $c['goods_name'];
                        $temp_goods[$k]['default_image'] = WEB_PHOTO_SRC . "/" . $c['default_image'];
                    }
                    $temp_goods[$k]['sort_order'] = $v['sort_order'];
                    $retult = $goods_spec->find(array('conditions'=>"goods_id = ".$v['goods_id']));
                    //声明一个库存数
                    $inventory = 0;
                    foreach ($retult as $key => $vvalue) {
                        $inventory += $vvalue['stock'];
                    }
                    //总库存
                    $temp_goods[$k]['total_inventory'] = $inventory;
                    $temp_goods[$k]['times'] = $c['times']?$c['times']:"无";

                    $res_ss = $goods_spec->getSpecStockInfo($v['goods_id']);
                    foreach ($res_ss as $key => $value) {
                        $value['international_code'] && !in_array($value['international_code'],$in_array)  ?  $in_array[] = $value['international_code'] : NULL;
                        $value['stock_name'] && !in_array($value['stock_name'],$stock_array) ? $stock_array[] = $value['stock_name'] : NULL;
                    }
                    $in_array ? $temp_goods[$k]['international_code'] = implode('<br>',$in_array) : NULL;
                    $stock_array ? $temp_goods[$k]['stock_name'] = implode('<br>',$stock_array) : NULL;

                }
                $ad['goods'] = $temp_goods;
            }
            $this->assign('ids',$ids);
            $this->assign('yes_or_no', $yes_or_no);
            $this->assign('info', $ad);
            $this->display('wish_activity.form.html');
        }else{
            $find_data     = $this->_wish_activityModel->find($ad_id);
            if (empty($find_data))
            {
                $this->show_warning('no_such_theme');
                return;
            }
            $data = array(
                'remark' => $_POST['remark'],
                'type' => $_POST['type']?$_POST['type']:1,
                'start_time' => strtotime($_POST['start_time']),
                'end_time' => strtotime($_POST['end_time']),
            );

            if($_FILES){
                //删除原图片
                if($_FILES['wish_activity_url'] && $find_data['wish_activity_url'] && $find_data['wish_activity_url'] != $_FILES['wish_activity_url']){
                    if(file_exists(WEB_PHOTO_SRC . '/' . $find_data['wish_activity_url'])){
                        unlink(WEB_PHOTO_SRC . '/' . $find_data['wish_activity_url']);
                    }
                }
                $logo =   $this->_upload($_FILES,'wish_activity_url');

                $logo && $data['wish_activity_url'] = $logo;
                if ($logo === false)
                {
                    return;
                }
            }

            //处理商品
            $goods_id = explode(',',$_POST['goods_id']);
            if(count($goods_id) < 1 || !$_POST['goods_id']){
                $this->show_warning('请选择商品！');
                return;
            }
            $sql = 'Delete from ecm_wish_goods where activity_id = '.$ad_id;
            $this->_wish_goodsModel->db->query($sql);

            foreach($goods_id as $k=>$v){
                $newArr['activity_id'] = $ad_id;
                $newArr['goods_id'] = $v;
                $newArr['sort_order'] = $_POST['goodsSorts'][$k];
                $this->_wish_goodsModel->add($newArr);
            }
            $rows=$this->_wish_activityModel->edit($ad_id, $data);
            if ($this->_wish_activityModel->has_error())
            {
                $this->show_warning($this->_wish_activityModel->get_error());
                return;
            }else{
                $this->admin_log("修改手机广告[".$_POST['ad_name']."]",1);
            }

            $this->show_message('保存成功',
                'back_list',        'index.php?app=wish_activity',
                '再次编辑',    'index.php?app=wish_activity&amp;act=edit&amp;activity_id=' . $ad_id);
        }
    }

    function drop(){
        $article_ids = isset($_GET['activity_id']) ? trim($_GET['activity_id']) : '';
        if (!$article_ids) {
            $this->show_warning('no_such_theme');

            return;
        }
        $message = 'drop_ok';
        $article = $this->_wish_activityModel->find(intval($article_ids));
        //删除原图片
        if($article['wish_activity_url']){
            if(file_exists(WEB_PHOTO_SRC . '/' . $article['wish_activity_url'])){
                unlink(WEB_PHOTO_SRC . '/' . $article['wish_activity_url']);
            }
        }
        if (!$this->_wish_activityModel->drop($article_ids)) {    //删除
            $this->show_warning($this->_wish_activityModel->get_error());
            return;
        }else{
            $sql = 'Delete from ecm_wish_goods where activity_id = '.$article_ids;
            $this->_wish_goodsModel->db->query($sql);
            $this->admin_log(Lang::get('del_theme'), 1);
        }
        $this->show_message('删除成功');
    }
    function iframe()
    {
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'goods_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'store_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'brand',
                'equal' => 'like',
            ),

        ));
        // 分类
        $cate_id = empty($_GET['cate_id']) ? 0 : intval($_GET['cate_id']);
        if ($cate_id > 0)
        {
            $cate_mod =& bm('gcategory');
            $cate_ids = $cate_mod->get_descendant_ids($cate_id);
            $conditions .= " AND cate_id" . db_create_in($cate_ids);
        }

        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
                $sort  = 'goods_id';
                $order = 'desc';
            }
        }
        elseif($_GET['sort'] == 4){ //今日上新
            $sort = 'add_time';
            $order = 'desc';
        }else {
            $sort  = 'goods_id';
            $order = 'desc';
        }
        $page = $this->_get_page(60);
        //断码

        //查询断码价
        $spec_model = & m('goodsspec');

        if($_GET['cut_off']){
            $sql = "select 
            ecm_storestock.stock_name, 
            ecm_goods.goods_id, 
            group_concat(ecm_goods_spec.spec_2) as spec2, 
            case when locate(',',group_concat(ecm_goods_spec.spec_2)) > 0 then 0 else 1 end as is_unique,
            ecm_goods_spec.stock
        from 
            ecm_goods, 
            ecm_goods_spec, 
            ecm_storestock 
        where 
            ecm_storestock.storestock_id = ecm_goods_spec.spec_3value and ecm_goods.goods_id = ecm_goods_spec.goods_id and ecm_goods_spec.stock > 0
        group by 
            ecm_goods.goods_id 
        having is_unique > 0";
            $db = &db('goods');
            $res_sql = $db->getall($sql);
            $conditions .= " AND g.goods_id" . db_create_in(array_column($res_sql,'goods_id'));
            var_dump($conditions);
        }

        $goodsSpec = & m('goodsspec');
        $storeStock = & m('storestock');

        //年代
        if($_GET['times']){
            $times = explode(',',$_GET['times']);
            $sql_time = '';
            foreach($times as $k=>$times_item){
                if($k == 0){
                    $sql_time = 'g.times like '."'%".trim($times_item)."%'";
                }else{
                    $sql_time .= ' OR g.times like '."'%".trim($times_item)."%'";
                }
            }
            $conditions .= " AND (".$sql_time.")";
        }

        //仓库 、国际码
        if($_GET['storestock_id'] || $_GET['international_code']){
            if($_GET['storestock_id'] && is_numeric($_GET['storestock_id'])){
                $where['conditions'] = 'spec_3value = '.$_GET['storestock_id'];
                $this->assign('storestock_id',$_GET['storestock_id']);
            }
            if($_GET['international_code']){
                $where['conditions'] = 'international_code like '."'%".$_GET['international_code']."%'";
                $this->assign('international_code',$_GET['international_code']);
            }
            if($_GET['storestock_id'] && is_numeric($_GET['storestock_id']) && $_GET['international_code']){
                $where['conditions'] = 'spec_3value = '.$_GET['storestock_id'].' AND international_code like'."'%".$_GET['international_code']."%'";
                $this->assign('storestock_id',$_GET['storestock_id']);
                $this->assign('international_code',$_GET['international_code']);
            }
            $goodsSpecInfo = $goodsSpec->find($where);
            $specList = array_values($goodsSpecInfo);
            $ids = '';
            if(!empty($specList)){
                foreach($specList as $k=>$v){
                    if($k == 0){
                        $ids = $v['goods_id'];
                    }else{
                        $ids .= ','.$v['goods_id'];
                    }
                }
                $conditions .= ' AND g.goods_id IN ('.$ids.')';
            }else{
                $conditions .= ' AND g.goods_id = 0 ';
            }
        }

        //是否上下架
        if($_GET['closed']){
            if($_GET['closed'] == 2){
                $closed = 0;
            }else{
                $closed = 1;
            }
            $conditions .= ' AND g.closed = '.$closed;
            $this->assign('closed',$_GET['closed']);
        }

        //库存数筛选
        if($_GET['count_from'] || $_GET['count_to']){
            if($_GET['count_from'] && !$_GET['count_to']){
                $count_from = $_GET['count_from'];
                $sql = "select * from (select sum(stock) as ccaa,goods_id from ecm_goods_spec group by goods_id ) as ccaa where ccaa >=$count_from";
            }elseif($_GET['count_to'] && !$_GET['count_from']){
                $count_to = $_GET['count_to'];
                $sql = "select * from (select sum(stock) as ccaa,goods_id from ecm_goods_spec group by goods_id ) as ccaa where ccaa <=$count_to";
            }else{
                $count_to = $_GET['count_to'];
                $count_from = $_GET['count_from'];
                $sql = "select * from (select sum(stock) as ccaa,goods_id from ecm_goods_spec group by goods_id ) as ccaa where (ccaa >=$count_from and ccaa<=$count_to)";
            }
            $info = $goodsSpec->db->query($sql);
            while ($chat = $goodsSpec->db->fetchRow($info)) {
                $chat_listOld[] = $chat;
            }
            if(!empty($chat_listOld)){
                $wish_ids = '';
                foreach($chat_listOld as $k=>$v){
                    if($k == 0){
                        $wish_ids = $v['goods_id'];
                    }else{
                        $wish_ids .= ','.$v['goods_id'];
                    }
                }
                $conditions .= " AND g.goods_id in (".$wish_ids.")";
            }
            $this->assign('count_from',$_GET['count_from']);
            $this->assign('count_to',$_GET['count_to']);
        }

        //价格筛选
        if($_GET['price_from'] || $_GET['price_to']){
            if($_GET['price_from'] && !$_GET['price_to']){
                $price_from = $_GET['price_from'];
                $sql = "select * from (select price as ccaa,goods_id from ecm_goods_spec group by goods_id ) as ccaa where ccaa >=$price_from";
            }elseif($_GET['price_to'] && !$_GET['price_from']){
                $price_to = $_GET['price_to'];
                $sql = "select * from (select price as ccaa,goods_id from ecm_goods_spec group by goods_id ) as ccaa where ccaa <=$price_to";
            }else{
                $price_to = $_GET['price_to'];
                $price_from = $_GET['price_from'];
                $sql = "select * from (select price as ccaa,goods_id from ecm_goods_spec group by goods_id ) as ccaa where (ccaa >=$price_from and ccaa<=$price_to)";
            }
            $info_price = $goodsSpec->db->query($sql);
            while ($chat_price = $goodsSpec->db->fetchRow($info_price)) {
                $chat_listOld_price[] = $chat_price;
            }
            if(!empty($chat_listOld_price)){
                $wish_ids_price = '';
                foreach($chat_listOld_price as $k=>$v){
                    if($k == 0){
                        $wish_ids_price = $v['goods_id'];
                    }else{
                        $wish_ids_price .= ','.$v['goods_id'];
                    }
                }
                $conditions .= " AND g.goods_id in (".$wish_ids_price.")";
            }
            $this->assign('price_from',$_GET['price_from']);
            $this->assign('price_to',$_GET['price_to']);
        }
        $conditions = " AND g.wish_close = 1";
        $goods_list = $this->_goods_mod->get_list(array(
            'conditions' => "1 = 1" . $conditions,
            'count' => true,
            'order' => "$sort $order",
            'limit' => $page['limit'],
        ));
        foreach ($goods_list as $key => $goods)
        {
            $goods_list[$key]['cate_name'] = $this->_goods_mod->format_cate_name($goods['cate_name']);
            $goods_list[$key]['default_image']  =   WEB_PHOTO_SRC . "/" . $goods['default_image'];
            $goods_list[$key]['times']  =   $goods['times'];
//            //单独查询规格表中的标价
            $retult = $goodsSpec->find(array('conditions'=>"goods_id = ".$key));
            if(!empty($retult)) {
                $str['domestic_price'] = 0;
                $str['domestic_discount'] = '无';
                $str['hong_kong_price'] = 0;
                $str['hong_kong_discount'] = '无';

                //声明一个库存数
                $inventory = 0;
                $in_array = array();
                $stock_array = array();
                foreach ($retult as $k => $v) {
                    $inventory += $v['stock'];
                    if ($v['spec_3value'] == 25) {                    //国内仓标价
                        $str['domestic_price'] = $v['price'];
                        if($goods['market_price'] && $goods['market_price'] != 0.00){
                            $str['domestic_discount'] = sprintf('%.2f', $v['price'] / $goods['market_price']) . '折';//国内仓折扣
                        }else{
                            $str['domestic_discount'] = 0 . '折';//国内仓折扣
                        }
                    }
                    if ($v['spec_3value'] == 26) {
                        $str['hong_kong_price'] = $v['price'];
                        if($v['price'] && $v['price'] != 0.00 && $goods['market_price'] != 0.00){
                            $str['hong_kong_discount'] = sprintf('%.2f', $v['price'] / $goods['market_price']) . '折';//香港折扣
                        }else{
                            $str['hong_kong_discount'] = 0 . '折';//香港折扣
                        }
                    }
                }
                $res_ss = $goodsSpec->getSpecStockInfo($key);
                foreach ($res_ss as $k => $v) {
                    $v['international_code'] && !in_array($v['international_code'],$in_array)  ?  $in_array[] = $v['international_code'] : NULL;
                    $v['stock_name'] && !in_array($v['stock_name'],$stock_array) ? $stock_array[] = $v['stock_name'] : NULL;


                }
                $in_array ? $goods_list[$key]['international_code'] = implode('<br>',$in_array) : NULL;
                $stock_array ? $goods_list[$key]['stock_name'] = implode('<br>',$stock_array) : NULL;
                $goods_list[$key]['domestic_price'] = $str['domestic_price'];
                $goods_list[$key]['domestic_discount'] = $str['domestic_discount'];
                $goods_list[$key]['hong_kong_price'] = $str['hong_kong_price'];
                $goods_list[$key]['hong_kong_discount'] = $str['hong_kong_discount'];
                //总库存
                $goods_list[$key]['total_inventory'] = $inventory;

            }
        }

        $this->assign('goods_list', $goods_list);

        $page['item_count'] = $this->_goods_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

        // 第一级分类
        $cate_mod =& bm('gcategory', array('_store_id' => 0));
        $this->assign('gcategories', $cate_mod->get_options(0, true));

        //仓库
        $this->assign('storeStock',$storeStock->get_options());

        $this->assign('cut_off', $_GET['cut_off']? 1 : 0); //是否有查询条件
        $this->import_resource(array('script' => 'mlselection.js,inline_edit.js '));
        $this->display('goods.iframe.html');
    }


}